//
//  UIViewController+Extension.m
//  Furniture
//
//  Created by 王小娜 on 2017/1/20.
//  Copyright © 2017年 beyondSoft. All rights reserved.
//

#import "UIViewController+Extension.h"
#import <objc/runtime.h>

#define AreaBtn @"NavigationBarTitleViewAreaBtn"

@implementation UIViewController (Extension)

//适用范围，tabbar的子视图都是NavigationController，其它情况可以根据情况调整
+ (UIViewController *)getCurrentViewController{
    
    UIViewController * result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app的windowLevel是UIWindowLevelNormal，如果不是，找到是UIWindowLevelNormal的Window
    if (window.windowLevel != UIWindowLevelNormal) {
        
        NSArray * windows = [[UIApplication sharedApplication] windows];
        for (UIWindow * tempWindow in windows) {
            
            if (tempWindow.windowLevel == UIWindowLevelNormal) {
                window = tempWindow;
                break;
            }
        }
    }
    id nextResponder = nil;
    UIViewController * appRootVC = window.rootViewController;
    //如果是present上来的vc，则appRootVC.presentedViewController不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        
        UIView * frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]]) {
        
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.selectedViewController;
        result = nav.childViewControllers.lastObject;
        
    }else if ([nextResponder isKindOfClass:[UINavigationController class]]){
        
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        result = nextResponder;
    }
    
    return result;
}

- (void)setUIInterfaceOrientationPortrait{
    [self orientationToPortrait:UIInterfaceOrientationPortrait];
}

- (void)setUIInterfaceOrientationLandscapeLeft{
    [self orientationToPortrait:UIInterfaceOrientationLandscapeLeft];
}
// 当回到原来的视图时, 如果希望这个视图还是竖屏, 可强制旋转一下
//强制旋转屏幕
- (void)orientationToPortrait:(UIInterfaceOrientation)orientation {
    SEL selector = NSSelectorFromString(@"setOrientation:");
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
    [invocation setSelector:selector];
    [invocation setTarget:[UIDevice currentDevice]];
    int val = orientation;
    [invocation setArgument:&val atIndex:2];//前两个参数已被target和selector占用
    [invocation invoke];
    
}
#pragma mark--设置navigationbar的返回按钮
- (void)setBackBtn{
    UIView * leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    UIImageView * imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, 18, 18)];
    imageview.image = readImageFromImageName(@"icon_outline_back");
    imageview.userInteractionEnabled = YES;
    [leftView addSubview:imageview];
    UILabel * label = [UILabel new];
    label.frame = CGRectMake(20, 0, 40, 44);
    label.text = @"";
    label.textColor = COLOR_TITLE;
    label.userInteractionEnabled = YES;
    [leftView addSubview:label];
    UITapGestureRecognizer * tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backClick)];
    [leftView addGestureRecognizer:tap1];
    UIBarButtonItem * backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];
    self.navigationItem.leftBarButtonItem = backButtonItem;
}

- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark--设置navigationbar的titleView
- (void)setAreaBtn:(UIButton *)areaBtn{
    objc_setAssociatedObject(self, AreaBtn, areaBtn, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIButton *)areaBtn{
    NSObject * objc = objc_getAssociatedObject(self, AreaBtn);
    if (objc && [objc isKindOfClass:[UIButton class]]) {
        return (UIButton *)objc;
    }
    return nil;
}

- (void)setNavigationBarTitleView{
    UIView * titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    self.areaBtn = [UIButton new];
    UIButton * imageBtn = [[UIButton alloc] init];
    [imageBtn setImage:[UIImage imageNamed:@"area"] forState:UIControlStateNormal];
    [imageBtn addTarget:self action:@selector(seleectArea) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:self.areaBtn];
    [titleView addSubview:imageBtn];
    
    [self.areaBtn makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(titleView.centerX);
        make.centerY.equalTo(titleView.centerY);
    }];
    [imageBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.areaBtn.right).offset(0);
        make.centerY.equalTo(titleView);
    }];
    
    [self.areaBtn setTitle:@"" forState:UIControlStateNormal];
    self.areaBtn.titleLabel.font = FONT(17);
    [self.areaBtn setTitleColor:COLOR_TITLE forState:UIControlStateNormal];
    [self.areaBtn addTarget:self action:@selector(seleectArea) forControlEvents:UIControlEventTouchUpInside];
    //fix Masonry bug
        [titleView makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(100);
            make.height.equalTo(44);
        }];
    

    self.navigationItem.titleView = titleView;
}

- (void)seleectArea{

  
}
#pragma mark-- 设置navigationbar的左侧按钮
- (void)setNavigationBarRightItemTitle:(NSArray *)titleArr image:(NSArray *)imageArr delegate:(id)delegate{
    
    NSMutableArray * leftItems = [NSMutableArray new];
    for (NSInteger i = 0; i < titleArr.count; i++) {
        
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 44)];

        UIImageView * imageBtn = [UIImageView new];
        imageBtn.image = readImageFromImageName(imageArr[i]);
        imageBtn.userInteractionEnabled = YES;
        [view addSubview:imageBtn];
        
        UILabel * titleBtn = [UILabel new];
        titleBtn.text = titleArr[i];
        titleBtn.textColor = COLOR_SUBTITLE;
        titleBtn.font = FONT(11);
        titleBtn.userInteractionEnabled = YES;
        [view addSubview:titleBtn];
        
        [imageBtn makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view.top).offset(3);
            make.centerX.equalTo(view);
        }];
        [titleBtn makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(imageBtn.bottom).offset(3);
            make.centerX.equalTo(view);
        }];
        
        SEL sel;
        if (i == 0) {
            sel = @selector(firstRightBarItemClicked);
        }
        if (i == 1) {
            sel = @selector(secondRightBarItemClicked);
        }
        //fix Masonry bug
       
            [view makeConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(40);
                make.height.equalTo(44);
            }];
        

        view.userInteractionEnabled = YES;
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:delegate action:sel];
        [view addGestureRecognizer:tap];
        
        UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:view];
        [leftItems addObject:leftItem];
    }
    self.navigationItem.rightBarButtonItems = leftItems;
}

//健康咨询 右侧按钮
- (void)setHealthyRightBar{
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"健康咨询" style:0 target:self action:@selector(HealthyAction)];
    
}
#pragma mark APP外包入口 健康咨询
- (void)HealthyAction{
    
    NSLog(@"APP外包入口 健康咨询");
    
}


-(void)popSystemAlertWithTitle:(NSString *)title msg:(NSString *)msg cancelTitle:(nullable NSString *)cancelTitle cancelBlock:(void (^_Nullable)(void))cancel sureTitle:(nullable NSString *)sureTitle sureBlock:(void (^_Nullable)(void))sure{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
    if ([msg length] > 0 && [title length] > 0) {
        NSMutableAttributedString *attrMessageStr = [[NSMutableAttributedString alloc]initWithString:msg];
        [attrMessageStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:colorFromHexStringWithAlpha(@"171A1D", 0.6)} range:NSMakeRange(0, attrMessageStr.length)];
        [alertVC setValue:attrMessageStr forKey:@"_attributedMessage"];
    }
    if (cancelTitle) {
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            if (cancel) {
                cancel();
            }
        }];
        [cancelAction setValue:colorFromHexString(@"A2A3A5") forKey:@"_titleTextColor"];
        [alertVC addAction:cancelAction];
    }
    if (sureTitle) {
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:sureTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //
            if (sure) {
                sure();
            }
        }];
        [alertVC addAction:sureAction];
    }
    [GETCURRENTCONTROLLER presentViewController:alertVC animated:YES completion:nil];
}

-(void)modalPresentVC:(UIViewController *_Nullable)vc viewAlpha:(CGFloat)alpha{
    self.definesPresentationContext = YES;
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    vc.view.backgroundColor = [UIColor colorWithWhite:0 alpha:alpha];
    [self presentViewController:vc animated:NO completion:nil];
}

- (void)popSystemAlertWithTitle:(nullable NSString *)title msg:(nullable NSString *)msg cancelBlock:(void (^)(void))cancel sureBlock:(void (^)(void))sure{
    [self popSystemAlertWithTitle:title msg:msg cancelTitle:REAPPString(@"取消") cancelBlock:cancel sureTitle:REAPPString(@"确定") sureBlock:sure];
}


@end
